package com.bwda.dsrs.filecenter.controller;
import com.bwda.dsrs.base.centerbase.response.CentreCutPageResponse;
import com.bwda.dsrs.base.centerbase.response.CentreListResponse;
import com.bwda.dsrs.base.centerbase.response.ResponseEntity;
import com.bwda.dsrs.base.util.CopyUtil;
import com.bwda.dsrs.base.util.StringUtil;
import com.bwda.dsrs.filecenter.domain.BusinessConstants;
import com.bwda.dsrs.filecenter.domain.condition.dbgroup.DbGroupCondition;
import com.bwda.dsrs.filecenter.domain.condition.dbgrouprel.DbGroupRelCondition;
import com.bwda.dsrs.filecenter.domain.condition.dbinfo.DbInfoCondition;
import com.bwda.dsrs.filecenter.domain.condition.dbscanresult.DbScanResultCondition;
import com.bwda.dsrs.filecenter.domain.condition.scanresulttable.ScanResultTableCondition;
import com.bwda.dsrs.filecenter.domain.exception.BusinessServiceException;
import com.bwda.dsrs.filecenter.domain.form.scanresulttable.ScanResultTableCreateForm;
import com.bwda.dsrs.filecenter.domain.form.scanresulttable.ScanResultTableQueryForm;
import com.bwda.dsrs.filecenter.domain.form.scanresulttable.ScanResultTableUpdateForm;
import com.bwda.dsrs.filecenter.domain.po.dbgroup.DbGroupPo;
import com.bwda.dsrs.filecenter.domain.po.dbgrouprel.DbGroupRelPo;
import com.bwda.dsrs.filecenter.domain.po.dbinfo.DbInfoPo;
import com.bwda.dsrs.filecenter.domain.po.scanresulttable.ScanResultTablePo;
import com.bwda.dsrs.filecenter.domain.vo.scanresulttable.ScanResultTableListVo;
import com.bwda.dsrs.filecenter.domain.vo.scanresulttable.ScanResultTableVo;
import com.bwda.dsrs.filecenter.service.DbGroupRelService;
import com.bwda.dsrs.filecenter.service.DbGroupService;
import com.bwda.dsrs.filecenter.service.DbInfoService;
import com.bwda.dsrs.filecenter.service.ScanResultTableService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Administrator
 */
@RestController
@RequestMapping("/b/scanresulttable")
@Api(value = "/b/scanresulttable", tags = "敏感扫描结果表")
public class ScanResultTableController extends BaseController {

	@Autowired
	private ScanResultTableService scanResultTableService;
	@Autowired
	private DbInfoService dbInfoService;
	@Autowired
	private DbGroupService dbGroupService;
	@Autowired
	private DbGroupRelService dbGroupRelService;

	@ApiOperation(value = "查询敏感扫描结果表",notes = "查询敏感扫描结果表",httpMethod = "GET")
	@RequestMapping(value = "/query", method = {RequestMethod.GET, RequestMethod.POST})
	public ResponseEntity<ScanResultTableVo> query(@ApiParam(value = "ID", required = true)@RequestParam Integer id) throws BusinessServiceException {
		ScanResultTablePo po = scanResultTableService.queryWithValid(id);
		ScanResultTableVo vo = CopyUtil.transfer(po, ScanResultTableVo.class);
		return getSuccessResult(vo);
	}

	@ApiOperation(value = "查询敏感扫描结果表数量",notes = "查询敏感扫描结果表数量",httpMethod = "GET")
	@RequestMapping(value = "/queryCount", method = {RequestMethod.GET, RequestMethod.POST})
	public ResponseEntity<Integer> queryCount(@ModelAttribute@Valid ScanResultTableQueryForm form) throws BusinessServiceException {
		ScanResultTableCondition condition = this.getConditionByQueryForm(form);
		int count = scanResultTableService.queryCount(condition);
		return getSuccessResult(count);
	}

	@ApiOperation(value = "查询敏感扫描结果表列表",notes = "查询敏感扫描结果表列表",httpMethod = "GET")
	@RequestMapping(value = "/queryList", method = {RequestMethod.GET, RequestMethod.POST})
	public ResponseEntity<CentreListResponse<ScanResultTableVo>> queryList(@ModelAttribute@Valid ScanResultTableQueryForm form) throws BusinessServiceException {
		ScanResultTableCondition condition = this.getConditionByQueryForm(form);
		List<ScanResultTablePo> poList = scanResultTableService.queryList(condition);
		List<ScanResultTableVo> voList = CopyUtil.transfer(poList, ScanResultTableVo.class);
		return getSuccessResult(getListResponse(voList));
	}

	@ApiOperation(value = "查询敏感扫描结果表列表(带分页)",notes = "查询敏感扫描结果表列表(带分页)",httpMethod = "GET")
	@RequestMapping(value = "/queryPageList", method = {RequestMethod.GET, RequestMethod.POST})
	public ResponseEntity<CentreCutPageResponse<ScanResultTableVo>> queryPageList(@ModelAttribute@Valid ScanResultTableQueryForm form) throws BusinessServiceException {
		ScanResultTableCondition condition = this.getConditionByQueryForm(form);
		List<ScanResultTableVo> voList = new ArrayList<>();
		int count = scanResultTableService.queryCount(condition);
		if (count > 0) {
			List<ScanResultTablePo> poList = scanResultTableService.queryList(condition);
			voList = CopyUtil.transfer(poList, ScanResultTableVo.class);
		}
		return getSuccessResult(getPageResponse(form, count, voList));
	}

	@ApiOperation(value = "新增敏感扫描结果表",notes = "新增敏感扫描结果表",httpMethod = "POST")
	@RequestMapping(value = "/add", method = {RequestMethod.GET, RequestMethod.POST})
	public ResponseEntity<ScanResultTableVo> add(@ModelAttribute@Valid ScanResultTableCreateForm form) throws BusinessServiceException {
		ScanResultTablePo po = CopyUtil.transfer(form, ScanResultTablePo.class);
//		po.setId(RandomUtils.nextInt());
		scanResultTableService.insert(po);
		ScanResultTableVo vo = CopyUtil.transfer(po, ScanResultTableVo.class);
		return getSuccessResult(vo);
	}

	@ApiOperation(value = "修改敏感扫描结果表",notes = "修改敏感扫描结果表",httpMethod = "POST")
	@RequestMapping(value = "/update", method = {RequestMethod.GET, RequestMethod.POST})
	public ResponseEntity update(@ModelAttribute@Valid ScanResultTableUpdateForm form) throws BusinessServiceException {
		ScanResultTablePo po = CopyUtil.transfer(form, ScanResultTablePo.class);
		scanResultTableService.update(po);
		return getSuccessResult();
	}

	@ApiOperation(value = "删除敏感扫描结果表",notes = "删除敏感扫描结果表",httpMethod = "POST")
	@RequestMapping(value = "/delete", method = {RequestMethod.GET, RequestMethod.POST})
	public ResponseEntity delete(@ApiParam(value = "ID", required = true)@RequestParam Integer id) throws BusinessServiceException {
		scanResultTableService.delete(id);
		return getSuccessResult();
	}

	@ApiOperation(value = "查询敏感表扫描结果表",notes = "查询敏感表扫描结果表",httpMethod = "GET")
	@RequestMapping(value = "/queryTableList", method = {RequestMethod.GET, RequestMethod.POST})
	public ResponseEntity<CentreListResponse<ScanResultTableListVo>> queryTableList(@ModelAttribute@Valid ScanResultTableQueryForm form) throws BusinessServiceException {
		//获取敏感字段
		DbInfoCondition dbInfoCondition = new DbInfoCondition();
		dbInfoCondition.setPageNum(form.getPageNum());
		dbInfoCondition.setPageSize(form.getPageSize());
		dbInfoCondition.setDelFlag(BusinessConstants.NumberConstant.ZERO);
		dbInfoCondition.setDbId(form.getDbId());
		int count = dbInfoService.queryCount(dbInfoCondition);
		List<ScanResultTableListVo> voList = new ArrayList<>();
		if (count > 0) {
			List<DbInfoPo> dbInfoPoList = dbInfoService.queryList(dbInfoCondition);
			if(!CollectionUtils.isEmpty(dbInfoPoList)){
				for (DbInfoPo d:dbInfoPoList
						) {
					ScanResultTableListVo scanResultTableListVo = new ScanResultTableListVo();
					scanResultTableListVo.setDbId(d.getDbId());
					scanResultTableListVo.setDbIp(d.getDbIp());
					scanResultTableListVo.setDbName(d.getDbName());
					ScanResultTableCondition scanResultTableCondition = new ScanResultTableCondition();
					scanResultTableCondition.setDbId(d.getDbId());
					scanResultTableCondition.setTableName(form.getTableName());
					scanResultTableCondition.setPageSize(Integer.MAX_VALUE);
					if(form.getMatchNums()!=null && form.getMatchNums()==0){
						scanResultTableCondition.setSensLabel("敏感数据");
					}
					List<ScanResultTablePo> scanResultTablePos = scanResultTableService.queryList(scanResultTableCondition);
					List<ScanResultTableVo> scanResultTableVos = CopyUtil.transfer(scanResultTablePos,ScanResultTableVo.class);
					if(!CollectionUtils.isEmpty(scanResultTableVos)){
						List<ScanResultTableListVo.TableList> tableLists = new ArrayList<>();
						for(ScanResultTableVo scanResultTableVo:scanResultTableVos){
							tableLists.add(CopyUtil.transfer(scanResultTableVo,ScanResultTableListVo.TableList.class));
						}
						scanResultTableListVo.setTableLists(tableLists);
					}
					voList.add(scanResultTableListVo);
				}
			}
		}
		return getSuccessResult(getPageResponse(form, count, voList));
	}

	/**
	 * ScanResultTableQueryForm转换为ScanResultTableCondition
	 *
	 * @param form
	 * @return
	 */
	private ScanResultTableCondition getConditionByQueryForm(ScanResultTableQueryForm form) {
		ScanResultTableCondition condition = CopyUtil.transfer(form, ScanResultTableCondition.class);
		return condition;
	}


	@ApiOperation(value = "新查询敏感扫描结果表列表(带分页)",notes = "新查询敏感扫描结果表列表(带分页)",httpMethod = "GET")
	@RequestMapping(value = "/queryTablePageList", method = {RequestMethod.GET, RequestMethod.POST})
	public ResponseEntity<CentreCutPageResponse<ScanResultTableVo>> queryTablePageList(@ModelAttribute@Valid ScanResultTableQueryForm form) throws BusinessServiceException {
		ScanResultTableCondition condition = this.getConditionByQueryForm(form);
		List<ScanResultTableVo> voList = new ArrayList<>();
		String userCode = getUserCode();
		List<Integer> dbIds = new ArrayList<>();
		int count = 0;
		//模糊查询，根据传入的数据库名称，查询对应的数据库ID
		DbInfoCondition dbInfoCondition = new DbInfoCondition();
		dbInfoCondition.setPageSize(Integer.MAX_VALUE);
		dbInfoCondition.setDelFlag(BusinessConstants.NumberConstant.ZERO);
		if(StringUtil.isNotEmpty(condition.getDbType())){
			dbInfoCondition.setDbType(condition.getDbType());
		}
		if(StringUtil.isNotEmpty(condition.getDbName())){
			dbInfoCondition.setDbName(condition.getDbName());
		}
		List<DbInfoPo> dbInfoPoList = dbInfoService.queryList(dbInfoCondition);
		if(!CollectionUtils.isEmpty(dbInfoPoList)){
			dbIds.addAll(dbInfoPoList.stream().map(p->p.getDbId()).collect(Collectors.toList()));
		}else{
			condition.setDbId(0);
		}
		if(!CollectionUtils.isEmpty(dbIds)){
//			dbIds = dbIdsByDbType.stream().filter(integer -> dbIdsByDbName.contains(integer)).collect(Collectors.toList());
			List<Integer> authDbIds = new ArrayList<>();
			//鉴权
			for (Integer dbId:dbIds
			) {
				DbGroupRelCondition dbGroupRelCondition = new DbGroupRelCondition();
				dbGroupRelCondition.setPageSize(Integer.MAX_VALUE);
				dbGroupRelCondition.setDbId(dbId);
				List<DbGroupRelPo> dbGroupRelPos = dbGroupRelService.queryList(dbGroupRelCondition);
				if("sysadmin".equals(getUserCode())){
					authDbIds.add(dbId);
				}
				else{
					if(!CollectionUtils.isEmpty(dbGroupRelPos)){
						for (Integer groupId:dbGroupRelPos.stream().map(p->p.getGroupId()).collect(Collectors.toList())
						) {
							DbGroupPo dbGroupPo = dbGroupService.query(groupId);
							if(dbGroupPo!=null && StringUtils.isNotBlank(dbGroupPo.getAdminUserCode()) && dbGroupPo.getAdminUserCode().equals(userCode) ){
								authDbIds.add(dbId);
							}
						}
					}
				}
			}
			if(!CollectionUtils.isEmpty(authDbIds)){
				condition.setDbIdList(authDbIds.stream().distinct().collect(Collectors.toList()));
				if(StringUtil.isNotEmpty(condition.getSensLabel())){
					condition.setSensLabelList(Arrays.asList(form.getSensLabel().split(",")));
				}
				count = scanResultTableService.queryCount(condition);
				if (count > 0) {
					List<ScanResultTablePo> poList = scanResultTableService.queryTablePageList(condition);
					voList = CopyUtil.transfer(poList, ScanResultTableVo.class);
				}
			}
		}
		return getSuccessResult(getPageResponse(form, count, voList));
	}


}